<?php

namespace App\Jobs\RemoveDelCatalogData;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;


class DelOriginal implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $list = DB::table('copy_table_logs')
            ->where('status', 1)
            ->select('id', 'part_company_id', 'project_classify_id', 'table_name1', 'table_name2', 'is_have_pdf')
            ->get();
        if ($list->isNotEmpty()) {
            $list = $list->toArray();
            foreach ($list as $val) {
                Schema::drop($val->table_name1);
                Schema::rename($val->table_name2, $val->table_name1);
                if ($val->is_have_pdf) {
                    $catalogTable = "book_catalogs_{$val->part_company_id}_{$val->project_classify_id}";
                    $pdfTable     = "book_catalog_pdfs_{$val->part_company_id}_{$val->project_classify_id}";
                    DB::table($catalogTable)
                        ->select('id', 'pre_id')
                        ->chunkById(1000, function ($list2) use ($pdfTable) {
                            UpdatePdfTable::dispatch($list2, $pdfTable);
                        });
                    Schema::table($val->table_name1, function (Blueprint $table) {
                        $table->dropColumn('pre_id');
                    });
                }
                DB::table('copy_table_logs')->where('id', $val->id)->update(['status' => 2]);
            }
        }
    }

}
